require "hpricot"

class HtmlResult
  $template = "
<html>
<head>
<style>
 .ctl{table-layout:fixed}
 .ctl td{white-space:wrap;padding:2px}
 table{border-collaps: collapse; border: 1px solid #666}
 th, td{padding: 0.1em 1em}
 caption{font-size: 1.2em; font-weight: bold; margin: 1em 0}
</style>
</head>
<body>
<table cellSpacing='0' cellpadding='1' width='100%' class='ctl' border='1' bgcolor='#E7E7EF'>
    <caption></caption>
    <thead>
        <tr>
            <th bgcolor='#A3D5E4'>Test Name</th>
            <th bgcolor='#A3D5E4'>Details</th>
        </tr>
    </thead>
    <tfoot>
        <tr>
            <th>Tests</th>
            <td name='test_count' align='center'></td>
        </tr>
        <tr>
            <th>Assertions</th>
            <td name='assertion_count'align='center'></td>
        </tr>
        <tr>
            <th>Failures</th>
            <td name='failure_count'align='center'></td>
        </tr>
        <tr>
            <th>Errors</th>
            <td name='error_count'align='center'></td>
        </tr>
    </tfoot>
    <tbody>
    </tbody>
</table>
</body>
</html>"

  def initialize(suite_name)
    t = Time.now
    @file_name = "#{suite_name}_#{t.mon}#{t.day}_#{t.hour}#{t.min}#{t.sec}.html"
    @doc = Hpricot($template)
  end

  def update
    Dir.mkdir("result") unless File.directory?("result")
    File.open(".\\result\\" + @file_name, "w") do |file|
      file.write(@doc)
    end
    return @file_name
  end

  private :update

  def write_caption(text)
    @doc.at("//caption").inner_html = text
  end 

  def append(test_name, failure=nil)
    idx = test_name.index("(")
    write_caption(test_name[idx+1..-2])
    test_name = test_name[5..idx-1].gsub(/_/, " ")
    if failure
      @doc.search("//tbody").append("
            <tr bgcolor='#CC2431'>
                <td align='left'>#{test_name}</td>
                <td>#{failure.long_display}</td>
            </tr>")
    else
      @doc.search("//tbody").append("
            <tr bgcolor='#7EE34B'>
                <td align='left'>#{test_name}</td>
                <td></td>
            </tr>")
    end
    update
  end

  def count_update(result)
    @doc.at("//td[@name='test_count']").inner_html = result.run_count.to_s
    @doc.at("//td[@name='assertion_count']").inner_html = result.assertion_count.to_s
    @doc.at("//td[@name='failure_count']").inner_html = result.failure_count.to_s
    @doc.at("//td[@name='error_count']").inner_html = result.error_count.to_s
    update
  end
end